<template>
  <div class="addVideo">
    <h3>上传/编辑视频</h3>
    <el-form
      :model="addForm"
      :rules="rules"
      ref="addForm"
      label-width="100px"
      class="addForm"
    >
      <el-row>
        <el-col :span="10">
          <el-form-item label="食安标题" prop="safetyTitle">
            <el-input v-model="addForm.safetyTitle"       maxlength="50"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="食安分类" prop="safetyCategory">
            <div class="safetyCategory">
              <el-input
                    maxlength="50"
                v-model="addForm.safetyCategory"
                placeholder="请输入食安分类"
              ></el-input>
              <el-select
                value=""
                placeholder=""
                allow-create
                @change="selectChange"
              >
                <el-option
                  :label="item"
                  :value="item"
                  v-for="(item, index) in list"
                  :key="index"
                ></el-option>
              </el-select>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否推荐">
            <el-checkbox v-model="addForm.isrecommend" true-label="1" false-label="0" checked>
              推荐显示</el-checkbox
            >
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="视频封面" class="required">
            <el-upload
              list-type="picture-card"
              accept="image/*"
              :on-preview="handlePictureCardPreview"
              :action="$upload"
              :headers="$headers()"
              :limit="1"
              :class="{ hide: hideUpload }"
              :file-list="unitModuleTaskFileSaveRequestList"
              :on-error="onError"
              :on-success="handleAvatarSuccess"
              :on-remove="onRemove"
              :before-remove="beforeRemove"
              :before-upload="
                (e) => {
                  return $beforeAvatarUpload(e);
                }
              "
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="上传视频" class="is-required">
            <el-upload
              accept="video/*"
              drag
              :action="$uploadVIDEO"
               :headers="$headers()"
              :limit="1"
              :file-list="unitModuleTaskvideoSaveRequestList"
              :on-success="handleVideoSuccess"
              :before-remove="beforeRemove"
              :on-remove="onRemoveVideo"
              :before-upload="beforeAvatarUpload"
              :on-preview="preview"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                只能上传一个MP4文件,不超过500M
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <el-col :span="8">
        <el-row type="flex" justify="end" :gutter="30">
          <el-col :span="5">
            <el-button type="primary" @click="onSave">保存</el-button>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="saveAndSet">保存并下发</el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-dialog
      destroy-on-close
      title="查看视频"
      :visible.sync="dialogVisible"
      width="40%"
    >
      <el-row type="flex" justify="center">
        <video
          controls
          :src="addForm.videoUrl"
          height="200px"
          width="80%"
        ></video>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <video
      controls
      id="upvideo"
      :src="addForm.videoUrl"
      height="0"
      width="0"
    ></video>
    <el-dialog :visible.sync="dialogImage">
      <img width="100%" :src="addForm.coverImg" alt="" />
    </el-dialog>
  </div>
</template>
<script>
export default {
  props: {},
  data() {
    return {
      addForm: {
        coverImg: "",
        creaeUnitId: "23342113",
        creaeUnitName: "苏州市市场监督管理局",
        id: "",
        isrecommend: 0,
        safetyCategory: "",
        safetyState: 0,
        safetyTitle: "",
        videoUrl:"",
      },
      unitModuleTaskFileSaveRequestList: [],
      unitModuleTaskvideoSaveRequestList: [],
      imageUrl: "",
      dialogVisible: false,
      dialogImage: false,
      list: [],
      rules: {
        safetyTitle: [
          { required: true, message: "请输入食安标题", trigger: "blur" },
        ],
        safetyCategory: [
          { required: true, message: "请输入食安分类", trigger: "change" },
        ],
      },
      loading: null,
    };
  },
  computed: {
    hideUpload() {
      return this.unitModuleTaskFileSaveRequestList.length >= 1;
    },
  },
  created() {
    this.findSafetyCategory();
    if (sessionStorage.getItem("classroom")) {
      let data = JSON.parse(sessionStorage.getItem("classroom"));
      this.addForm = data;

      this.unitModuleTaskFileSaveRequestList = [
        {
          url: data.coverImg,
        },
      ];
      this.unitModuleTaskvideoSaveRequestList = [
        {
          url: data.videoUrl,
          name: data.videoUrl,
        },
      ];
      //             coverImg: "http://172.16.92.155:9031/ssa-pc-api/fjimg/20211009/1fb9f4dd2ef34789895371bdc4ff9908.png"
      // creaeUnitId: "23342113"
      // creaeUnitName: "苏州市市场监督管理局"
      // createTime: "2021-10-09"
      // id: "1168539977684877312"
      // isrecommend: "否"
      // playbackVolume: "0"
      // releaseDate: "2021-10-09"
      // safetyCategory: "22"
      // safetyState: "待发布"
      // safetyTitle: "12"
      // updateTime: "2021-10-09"
      // videoUrl: "http://172.16.92.155:9031/ssa-pc-api/fjimg/20211009/e3e16ce51eb94fd7910cef92738662e1.mp4"
    }
  },
  mounted() {},
  methods: {
    findSafetyCategory() {
      this.$http
        .findSafetyCategory({
          params: this.addForm,
        })
        .then((res) => {
            this.list = res.data;
        })
        .catch((res) => {
          console.log(res);
        });
    },
    handleAvatarSuccess(e) {
      if (e.code == 200) {
        this.addForm.coverImg = this.$uploadURL + e.data;
        this.unitModuleTaskFileSaveRequestList.push({
          url: this.$uploadURL + e.data,
        });
      }
    },
    handleVideoSuccess(e) {
      this.loading && this.loading.close();
        this.addForm.videoUrl = e.data;
      //    this.$nextTick(() => {
      //  let video = document.getElementById("upvideo");
      //   let source = document.createElement("source");
      //   source.src = this.$uploadURL + e.data;
      //   source.type = "video/mp4";
      //   video.appendChild(source);
      //   video.addEventListener("loadeddata",()=> {
      //     var canvas = document.createElement("canvas");
      //     canvas.width = "320";
      //     canvas.height = "320";
      //     canvas
      //       .getContext("2d")
      //       .drawImage(video, 0, 0, canvas.width, canvas.width);
      //     let imgsrc = canvas.toDataURL("image/png");
      //     this.addForm.coverImg=imgsrc
      //       this.unitModuleTaskFileSaveRequestList.push({
      //     url: imgsrc,
      //   });
      // });
      //   });
    },
    onError(e) {
      this.$error("上传失败");
    },
    preview(e) {
      this.dialogVisible = true;
    },
    onSave() {
      this.addForm.safetyState = 0;
      this.save();
    },
    async save() {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          if (!this.addForm.videoUrl) return this.$error("请上传视频");
          // if (!this.addForm.coverImg) return this.$error("请上传封面");
          let data = null;
          if (this.addForm.id) {
            data = await this.$http.updateFindSafety(this.addForm);
          } else {
            data = await this.$http.saveClassroom(this.addForm);
          }

          if (data.code == 200) {
            this.$success(data.msg);
            setTimeout(() => {
              this.$router.go(-1);
            }, 500);
          } else {
            this.$error(data.msg);
          }
        }
      });
    },
    saveAndSet() {
      this.addForm.safetyState = 1;
      this.save();
    },
    handlePictureCardPreview() {
      this.dialogImage = true;
    },
    onRemove() {
      this.addForm.coverImg = "";
      this.unitModuleTaskFileSaveRequestList = [];
    },
    onRemoveVideo() {
      this.addForm.videoUrl = "";
      this.unitModuleTaskvideoSaveRequestList = [];
    },
    beforeRemove(file) {
      if (file && file.status === "success") {
        return this.$confirm("确定删除这一项吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
      }
    },
    selectChange(e) {
      this.addForm.safetyCategory = e;
    },
    beforeAvatarUpload(e) {
      this.loading = this.$loading({
        lock: true,
        text: "上传中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      return this.$beforeAvatarUpload(e, 2);
    },
  },
  destroyed() {
    sessionStorage.removeItem("classroom");
  },
  // updateFindSafety
};
</script>

<style scoped lang="scss">
.required {
  /deep/.hide .el-upload--picture-card {
    display: none;
  }
}
.safetyCategory {
  display: flex;
  border: 1px solid #dcdfe6;
  /deep/.el-input__inner {
    border: none !important;
  }
  /deep/.el-input__inner {
    border: none;
  }

}
.addVideo{
  /*去除upload组件过渡效果*/
/deep/ .el-upload-list__item {
  transition: none !important;
}
}
</style>
